package com.hnnu.shoppingtoghter.demo.interceptor;

import com.hnnu.shoppingtoghter.demo.entity.SysUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*** @Description: 拦截器
 * @Author: PDY
 * @CreateTime： 2022/7/3 2:29 
 */
@Component

public class LoginInterceptor implements HandlerInterceptor{
    /**
     * 在调用控制器方法之前触发
     *      返回false：拦截请求
     *      返回true：放行
      * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /** 第一步： 获取用户请求URL */
       String URI = request.getRequestURI();
        String URL = request.getRequestURL().toString();
        System.out.println("进入到了登录拦截器第一层 LoginInterceptor - preHandle URI = " + URI + "; URL = " + URL );
        /** 第二步： 判断请求是否需要拦截，或者说是否需要在登录的情况下访问 */
        Object userObj = request.getSession().getAttribute("user");//从session 中拿取用户登录信息，判断用户是否登录
        if(null == userObj) {
           System.out.println("登录拦截器 LoginInterceptor 执行了 preHandle 将 【" + URI + "】已拦截，拦截原因：未登录！ ");
           //  return "login";  //转发请求
           response.sendRedirect("/login");//重定向
           return false;
       }
        //用户已登录，请求放行
        return true;
   }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入到了登录拦截器第二层 LoginInterceptor - postHandle");
        /*SysUser user = new SysUser();
        user.setUserName("张三");
        request.getSession().setAttribute("user", user);
        request.getSession().removeAttribute("user");*/
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("进入到了登录拦截器第三层 LoginInterceptor - afterCompletion");
    }
}
